<?php
/**
* Red RUgolok
* @version $Id: item.class.php
* @package RUgolok
* @subpackage item.class.php
* @author el_leo and manicon
* @copyright (C) el_leo and manicon, www.rugolok.de
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );



/**
 * Class Item
 *
 * <b>What does it do?</b>
 * It manages the (creative) items. It can insert new items, update or manipulate own fields.
 *
 * <b>How does it work?</b>
 * You instanciate the class whith id number of an item, that allready exists or
 * with <i>null</i>, if you want to create a new one.
 *
 * After you fill out all fields, you should save the item by calling {@link process}.
 *
 */
class Item {

  /**
   * ID number of an item
   *
   * @access public
   * @var int
   */
    var $id;

  /**
   * Date, the item was generated
   *
   * @access public
   * @var string
   */
    var $date;

    /**
     * Date, the item was updated last time
     *
     * @access public
     * @var string
     */
    var $last_update;

    /**
     * Holds eventual error message in plain english
     *
     * @access public
     * @var string
     */
    var $error;

    /**
     * Points
     *
     * @access public
     * @var float
     */
    var $points;

    /**
     * Number of marks
     *
     * @access public
     * @var int
     */
     var $num_marks;

    /**
     * Average weight
     *
     * @access public
     * @var int
     */
     var $avg_weight;

    /**
     * Fieldname of the file
     *
     * @access public
     * @var string
     */
    var $file_field;

    /**
     * Timestamp to prevent multiple insertion
     * or to identify the row after it was written to database
     *
     * @access public
     * @var int
     */
     var $checkID;

  /**
     * Let the user rate this item or not
     *
     * @access public
     * @var bool
     */
     var $rated;

     /**
     * Views
     *
     * @access public
     * @var int
     */
     var $views;

     /**
     * Comments
     *
     * @access public
     * @var int
     */
     var $comments;

    /**
     * Author(s)
     *
     * @access public
     * @var Array
     */
     var $authors;

     /**
     * SMF Topic ID
     *
     * @access public
     * @var int
     */
     var $smf_topic_id;


// fields could be updated by user

  /**
     * Title / Name
     *
     * @access public
     * @var string
     */
    var $title;

    /**
     * Type ID number - type of the item
     *
     * @access public
     * @var int
     */
    var $type_id;


  /**
     * Description
     *
     * @access public
     * @var string
     */
    var $description;

    /**
     * Main text body
     *
     * @access public
     * @var string
     */
    var $text;

    /**
     * Filename
     *
     * @access public
     * @var string
     */
    var $file;

    /**
     * ID of the group
     *
     * @access public
     * @var int
     */
    var $group_id;

  /**
     * ID of the group
     *
     * @access public
     * @var int
     */
    var $language_id;


    /**
     * ID of the mood
     *
     * @access public
     * @var int
     */
    var $mood_id;

    /**
     * Keywords separated bei ','
     *
     * @access public
     * @var string
     */
    var $keywords;

    /**
     * Author was inspired by...
     *
     * @access public
     * @var string
     */
    var $inspired_by;

    /**
     * Is published?
     * Can be set just one time (item can not be unpublished, if it was published once)
     *
     * @access public
     * @var bool
     */
    var $published;

    /**
     * Type name
     */
     var $type_name;

  /**
   * Constructor
   *
   * Initialize some varibales
   *
   * @param int $id ID Number of a item
   */
  function Item( $id = '' ) {
    global $database;

    if(is_int($id)) {
      $item = null;
      $this->id = $id;
      $query = "SELECT * FROM #__redrugolok_items WHERE id = '".$id."'";
      $database->setQuery( $query );
      $database->loadObject( $item );
      $this = $item;
      Item::setAuthors(&$this);
      Item::setTypeName();
    }
  }

  /**
   * Write the name of the type to this object
   */
  function setTypeName() {
    if( isset( $this->type_id ) ) {
      $type = getItemType($this->type_id);
      $this->type_name = $type->name;
    } else
      $this->type_name = '';
  }

  /**
   * Set the authors in this object
   * authors
   */
  function setAuthors($item) {
    global $database;
    $query = "SELECT * FROM #__redrugolok_items_to_authors 
				WHERE item_id = '".$item->id."'";

    $database->setQuery($query);
    
    unset($item->authors);
    if(!$authors = $database->loadObjectList()){
    		$item->error = "Authors have not been selected";
    } else {
    		$index = 0;
    		foreach($authors as $author) {
    			$item->authors[$index]["jos_users_id"] = $author->author_id;
    			$item->authors[$index]["username"] = get_username($author->author_id);
    			$index++;
    		}
    }
  }

  /**
   * Set nubmer of views
   */
  function setViews() {
    global $database;
    $this->views = $this->views++;

  }

  /*function getAuthors() {
  	global $database;

  	$query = "SELECT * FROM #__redrugolok_items_to_authors, #__redrugolok_items WHERE #__redrugolok_items.id = #__redrugolok_items_to_authors.author_id";
	$database->setQuery($query);
	echo $query;

  	$this->authors = "testauthor";
  }*/

  /**
   * Show the list with authors
   */
  function htmlShowAuthors() {
    return "";
  }

  /**
   * Show the list with keyowrds
   */
  function htmlShowKeywords() {
    return "";
  }

  /**
   * Inserts new item
   *
   * @return bool true if inserted, false if fails {@link error}
   */
  function insert() {
    global $database, $Itemid, $my;

	// check the required fields
    if(!$this->title) {
      $this->error = "Title field is empty";
      return false;
    }

    if(!$this->type_id) {
      $this->error = "Type not selected";
      return false;
    }

    if(!$this->description) {
      $this->error = "No description";
      return false;
    }

	// check the required art of the item
    $typeObj = null;
    $query = "SELECT is_text, is_file FROM #__redrugolok_types WHERE id = '".$this->type_id."'";
    $database->setQuery($query);
    $database->loadObject($typeObj);

    if(!$this->text and $typeObj->is_text) {
      $this->error = "Main text";
      return false;
    }

    if(!$this->file and $typeObj->is_file) {
      $this->error = "No file attached";
      return false;
    }

	//$this->id = $item->id;
    // check authors

    foreach($this->authors as $author) {
	    $query = "SELECT id, name FROM #__users WHERE id = '".$author."'";
	    $database->setQuery($query);
	    $tmp = null;
	    if(!$database->loadObject($tmp)) {
	    	$error = true;
	    	$this->error = "User not found: ".$author."<br/>";
	    }  else {
	    		$query = "SELECT id, username FROM #__redrugolok_authors 
							WHERE jos_user_id = '".$author."' 
							AND category_id = '".$this->type_id."'";
	    		echo $query;
			    $database->setQuery($query);
			    $tmp = null;
			    if(!$database->loadObject($tmp)) {
			    	//Add author
			    	$username = get_username($author);
			    	$smf_id = smf_member_id($username);
			    	
			    	$query = "INSERT INTO #__redrugolok_authors (`jos_user_id`, `smf_member_id`, `username`)
								VALUES('".$author."', '".$smf_id."', '".$username."');";
			    	$database->setQuery($query);
			    	if(!$database->query()){
			    			$this->error = "Author not inserted";
			    	}
			    }  else {
			    		//update author
			    		$query = "UPDATE #__redrugolok_authors SET num_items = num_items+1, num_rated_items=num_rated_items+1 " .
       					"WHERE jos_user_id = '".$author."'";
					    $database->setQuery($query);
					    	if(!$database->query()){
					    			$this->error = "Number of items has not been updated";
					    	}
			    }
	    		
	    }
    }
   
    if($this->error) {
    	HTML_redrugolok::warning("The following authors were not found: <br />".$this->error);
    	return false;
    }

    
    
    unset($tmp);
 	$tmp->id = $this->id;
 	$tmp->title = $this->title;
 	$tmp->description = $this->description;
 	$tmp->text = $this->text;
 	$tmp->type_id = $this->type_id;
 	$tmp->date = $this->date;
 	$tmp->published = $this->published;
 	$tmp->rated = $this->rated;
 	$tmp->keywords = $this->keywords;
 	$tmp->inspired_by = $this->inspired_by;
 	$tmp->smf_topic_id =$this->smf_topic_id;
  	$tmp->views =$this->views;
  	$tmp->comments =$this->comments;	
 	$tmp->checkID = $this->checkID;

    // insert item
    if( !$database->insertObject('#__redrugolok_items', $tmp) ) {
      echo $this->error = "The following could not be inserted: <br/>";
      echo "<code>";
      print_r( $this );
      echo "</code>";
      echo "<br/>SQL error:<br/>";
      echo "<code>";
      echo $database->_errorMsg;
      echo "</code>";
      return false;
    }

    // get item id
    $query = "SELECT id FROM #__redrugolok_items WHERE checkID = '".$this->checkID."'";
    $database->setQuery( $query );

    $item = null;
    if ( !$database->loadObject( $item ) ) {
      $this->error = "Ups, somthing was wrong. The item could not be found in database. Please contact the administrator<br/>";
      $this->error .= "<code>".$query."</code>";
      HTML_redrugolok::warning($this->error);
      return false;
    } else {
    		$this->id = $item->id;
    	}

    foreach($this->authors as $author) {
	    $query = "INSERT INTO #__redrugolok_items_to_authors (`item_id`, `author_id`) " .
	        "VALUES(" .
	            " '".$this->id."', " .
	            " '".$author."')";
	    $database->setQuery( $query );
	    if ( !$database->query( $query ) ) {
	      $this->error = "Ups, somthing gone wrong. Please contact the administrator<br/>";
	      $this->error .= "<code>".$query."</code>";
	      HTML_redrugolok::warning($this->error);
	      return false;
	    }
    }
    
    

    
    
    Item::setAuthors(&$this);

    return true;

  }

  /**
   * TODO: Description insertItemToAuthor()
   *
   * @param int $author_id ID number of author
   * @return bool true if inserted, false if fails {@link error}
   */
  function updateItemToAuthor($author_id, $author_name) {
    global $database;

    $query = "UPDATE #__redrugolok_item_to_author SET author_id = '".$author_id."' " .
        "WHERE item_id = '".$this->id."'";

    $database->setQuery( $query );
    if( !$database->query() ) {
      $this->error = "The author could not be updated";
      return false;
    }
    else
      return true;
  }

  /**
   * Updates the item
   * TODO: Behandlung von "rated"
   *
   * @return bool true if updated, false if fails {@link error}
   */
  function update($this) {
    global $database;
     
    if(!$this->title) {
      $this->error = "Title field is empty";
      return false;
    }

    if(!$this->type_id) {
      print_r( $this );
      $this->error = "Type not selected";
      return false;
    }

    if(!$this->description) {
      $this->error = "No description";
      return false;
    }
    
  	if(!$this->authors) {
      $this->error = "No authors";
      return false;
    }

    $typeObj = null;
    $query = "SELECT is_text, is_file FROM #__redrugolok_types WHERE id = '".$this->type_id."'";
    $database->setQuery($query);
    $database->loadObject($typeObj);

    if(!$this->text and $typeObj->is_text) {
      $this->error = "Main text";
      return false;
    }

    if(!$this->file and $typeObj->is_file) {
      $this->error = "No file attached";
      return false;
    }

    if( $database->updateObject('#__redrugolok_items', &$this, 'id = '.$this->id.'') ) {
      echo "The item could not be updated";
      return false;
    }
    
 	// insert item
 	print_r($this);
 	$tmp->id = $this->id;
 	$tmp->title = $this->title;
 	$tmp->description = $this->description;
 	$tmp->text = $this->text;
 	$tmp->type_id = $this->type_id;
 	$tmp->last_update = time();
 	$tmp->published = $this->published;
 	$tmp->rated = $this->rated;
 	$tmp->keywords = $this->keywords;
 	$tmp->inspired_by = $this->inspired_by;
 	
 	echo "----------".$this->authors;
    if( !$database->updateObject('#__redrugolok_items', $tmp, 'id') ) {
      echo $this->error = "The following could not be updated: <br/>";
      echo "<code>";
      print_r( $this );
      echo "</code>";
      echo "<br/>SQL error:<br/>";
      echo "<code>";
      echo $database->_errorMsg;
      echo "</code>";
      return false;
    }
    return true;
  }

  /**
   * TODO: Description updateItemToAuthor()
   *
   * @param int $author_id ID number of author
   * @return bool true if updated, false if fails {@link error}
   */
 /* function updateItemToAuthor($author_id) {
    global $database;

    $query = "UPDATE #__redrugolok_item_to_author SET author_id = '".$author_id."' " .
        "WHERE item_id = '".$this->id."'";

    $database->setQuery( $query );
    if( !$database->query() ) {
      $this->error = "The author could not be updated";
      return false;
    }
    else
      return true;
  }*/

  /**
   * Updates the field {@link $points} of the item
   *
   * @param int $points the number of points
   * @return bool true if updated, false if error occupied {@link error}
   */
   function updatePoints($points) {
     global $database;

     $query = "UPDATE #__redrugolok_items SET ";
    $this->points = points;

     return false;
   }

   /**
   * Updates the field {@link $last_update} of the item
   *
   * @param int $points the number of points
   * @return bool true if updated, false if error occupied {@link error}
   */
   function updateDate($points) {
    global $database;
    $this->points = points;

     return false;
   }

}

?>